package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class ImageCleanupTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AliOssUtil aliOssUtil;

    private static final String UPLOADED_IMAGES_SET = "uploadedImages";
    private static final String USED_IMAGES_SET = "usedImages";

    // 每天午夜清理一次
    @Scheduled(cron = "0 0 0 * * ?")
    public void cleanUpUnusedImages() {
        // 计算 uploadedImages 和 usedImages 集合的差值
        //功能：返回在第一个集合（key1）中存在而在第二个集合（key2）中不存在的元素。
        Set<String> unusedImages = redisTemplate.opsForSet().difference(UPLOADED_IMAGES_SET, USED_IMAGES_SET);

        if (unusedImages != null && !unusedImages.isEmpty()) {
            for (String unusedImage : unusedImages) {
                // 删除 OSS 中的垃圾图片
                aliOssUtil.delete(unusedImage);
                // 从 Redis 中删除垃圾图片记录
                redisTemplate.opsForSet().remove(UPLOADED_IMAGES_SET, unusedImage);
            }
        }
    }

}
